// 第二遍
import axios, { type Method } from 'axios'
import { setUserInfo } from '@/stores'
import { showToast } from 'vant'
import router from '@/router'
const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const store = setUserInfo()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {
      showToast(res.data.message || '失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (res) => {
    const store = setUserInfo()
    if (res.response.status === 401) {
      store.delUser()
      router.push(`/login/returnURL${router.currentRoute.value.fullPath}`)
    }
    return Promise.reject(res)
  }
)
type Data<T> = {
  message: string
  code: number
  data: T
}
const request = <T>(url: string, method: Method, submitData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLocaleUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

// request('/','GET')

export { request }
